using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using ThridGroup.ERP.Application.Contracts.DTO;
using ThridGroup.ERP.Application.Contracts.ProductionSystem;
using Volo.Abp.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;

namespace ThridGroup.ERP.Web.Areas.ProductionSystem.Controllers
{
    [Area("ProductionSystem")]
    [Route("ProductionSystem/[controller]")]
    public class MaintenanceplanController : AbpController
    {
        private readonly IMaintenanceplanService _maintenanceplanService;
        private readonly ILogger<MaintenanceplanController> _logger;

        public MaintenanceplanController(
            IMaintenanceplanService maintenanceplanService,
            ILogger<MaintenanceplanController> logger)
        {
            _maintenanceplanService = maintenanceplanService;
            _logger = logger;
        }

        [HttpGet]
        [Route("")]
        [Route("Index")]
        public IActionResult Index()
        {
            _logger.LogInformation("访问点检保养计划管理页面");
            return View();
        }

        [HttpGet]
        [Route("Edit")]
        public async Task<IActionResult> Edit(int? id)
        {
            ViewBag.Id = id ?? 0;
            return View();
        }

        [HttpGet]
        [Route("GetMaintenanceplans")]
        public async Task<IActionResult> GetMaintenanceplans(string projectCode = null, string projectName = null, string projectType = null, string whethertoEnable = null, int page = 1, int limit = 10)
        {
            try
            {
                _logger.LogInformation($"开始获取点检保养计划列表, 页码: {page}, 每页数量: {limit}, 筛选条件: projectCode={projectCode}, projectName={projectName}, projectType={projectType}, whethertoEnable={whethertoEnable}");
                
                // 尝试从服务层获取数据
                List<MaintenanceplanDto> allData;
                try
                {
                    allData = await _maintenanceplanService.GetMaintenanceplans();
                    _logger.LogInformation($"从服务层获取点检保养计划列表成功，共获取{allData?.Count ?? 0}条记录");
                }
                catch (Exception serviceEx)
                {
                    _logger.LogError(serviceEx, "从服务层获取点检保养计划列表失败");
                    return Json(new { code = 1, msg = "获取数据失败：" + serviceEx.Message, count = 0, data = new List<MaintenanceplanDto>() });
                }
                
                // 检查获取的数据
                if (allData == null)
                {
                    _logger.LogWarning("服务层返回的点检保养计划列表为null");
                    return Json(new { code = 0, msg = "获取成功，但无数据", count = 0, data = new List<MaintenanceplanDto>() });
                }

                _logger.LogInformation($"搜索前总记录数: {allData.Count}");
                
                // 记录搜索前的状态分布
                var statusGroups = allData.GroupBy(x => x.WhethertoEnable ?? "null").ToList();
                foreach (var group in statusGroups)
                {
                    _logger.LogInformation($"状态 '{group.Key}' 的记录数: {group.Count()}");
                }

                // 应用筛选条件
                if (!string.IsNullOrWhiteSpace(projectCode))
                {
                    allData = allData.Where(x => x.ProjectCode.Contains(projectCode, StringComparison.OrdinalIgnoreCase)).ToList();
                    _logger.LogInformation($"按项目编码筛选后，剩余{allData.Count}条记录");
                }

                if (!string.IsNullOrWhiteSpace(projectName))
                {
                    allData = allData.Where(x => x.ProjectName.Contains(projectName, StringComparison.OrdinalIgnoreCase)).ToList();
                    _logger.LogInformation($"按项目名称筛选后，剩余{allData.Count}条记录");
                }

                if (!string.IsNullOrWhiteSpace(projectType))
                {
                    allData = allData.Where(x => x.ProjectType.Equals(projectType, StringComparison.OrdinalIgnoreCase)).ToList();
                    _logger.LogInformation($"按项目类型筛选后，剩余{allData.Count}条记录");
                }

                if (!string.IsNullOrWhiteSpace(whethertoEnable))
                {
                    _logger.LogInformation($"开始按状态筛选，目标状态: '{whethertoEnable}'");
                    
                    // 记录筛选前每条记录的状态
                    foreach (var item in allData.Take(10)) // 只记录前10条避免日志过多
                    {
                        _logger.LogInformation($"记录ID {item.Id}: 状态='{item.WhethertoEnable}', 是否匹配='{item.WhethertoEnable?.Equals(whethertoEnable, StringComparison.OrdinalIgnoreCase)}'");
                    }
                    
                    // 更灵活的状态匹配逻辑
                    allData = allData.Where(x => 
                    {
                        if (string.IsNullOrWhiteSpace(x.WhethertoEnable))
                            return false;
                            
                        // 清理空白字符
                        var cleanStatus = x.WhethertoEnable.Trim();
                        var cleanSearchTerm = whethertoEnable.Trim();
                        
                        // 直接匹配
                        if (cleanStatus.Equals(cleanSearchTerm, StringComparison.OrdinalIgnoreCase))
                            return true;
                            
                        // 兼容性匹配：启用状态
                        if (cleanSearchTerm.Equals("启用", StringComparison.OrdinalIgnoreCase))
                        {
                            return cleanStatus.Equals("启用", StringComparison.OrdinalIgnoreCase) ||
                                   cleanStatus.Equals("是", StringComparison.OrdinalIgnoreCase) ||
                                   cleanStatus.Equals("1", StringComparison.OrdinalIgnoreCase) ||
                                   cleanStatus.Equals("true", StringComparison.OrdinalIgnoreCase) ||
                                   cleanStatus.Equals("enabled", StringComparison.OrdinalIgnoreCase) ||
                                   cleanStatus.Equals("enable", StringComparison.OrdinalIgnoreCase) ||
                                   cleanStatus.Equals("on", StringComparison.OrdinalIgnoreCase) ||
                                   cleanStatus.Equals("active", StringComparison.OrdinalIgnoreCase);
                        }
                        
                        // 兼容性匹配：停用状态
                        if (cleanSearchTerm.Equals("停用", StringComparison.OrdinalIgnoreCase))
                        {
                            return cleanStatus.Equals("停用", StringComparison.OrdinalIgnoreCase) ||
                                   cleanStatus.Equals("否", StringComparison.OrdinalIgnoreCase) ||
                                   cleanStatus.Equals("0", StringComparison.OrdinalIgnoreCase) ||
                                   cleanStatus.Equals("false", StringComparison.OrdinalIgnoreCase) ||
                                   cleanStatus.Equals("disabled", StringComparison.OrdinalIgnoreCase) ||
                                   cleanStatus.Equals("disable", StringComparison.OrdinalIgnoreCase) ||
                                   cleanStatus.Equals("off", StringComparison.OrdinalIgnoreCase) ||
                                   cleanStatus.Equals("inactive", StringComparison.OrdinalIgnoreCase);
                        }
                        
                        return false;
                    }).ToList();
                    
                    _logger.LogInformation($"按状态筛选后，剩余{allData.Count}条记录");
                    
                    // 记录筛选后的结果
                    foreach (var item in allData)
                    {
                        _logger.LogInformation($"筛选后记录ID {item.Id}: 状态='{item.WhethertoEnable}'");
                    }
                }

                // 按ID排序
                var orderedData = allData.OrderBy(x => x.Id).ToList();
                
                // 计算总记录数
                int totalCount = orderedData.Count;
                
                // 进行分页
                var pagedData = orderedData
                    .Skip((page - 1) * limit)
                    .Take(limit)
                    .ToList();

                _logger.LogInformation($"成功获取点检保养计划列表，总记录数: {totalCount}, 当前页记录数: {pagedData.Count}");
                
                // 记录一下返回的数据结构，便于调试
                var sampleData = pagedData.FirstOrDefault();
                if (sampleData != null)
                {
                    _logger.LogInformation($"示例数据: Id={sampleData.Id}, ProjectCode={sampleData.ProjectCode}, ProjectName={sampleData.ProjectName}");
                }
                
                // 返回标准格式的数据，使用count表示总记录数
                return Json(new { 
                    code = 0, 
                    msg = "获取成功", 
                    count = totalCount, 
                    data = pagedData 
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取点检保养计划列表失败");
                _logger.LogError($"异常详情：{ex.Message}, StackTrace: {ex.StackTrace}");
                if (ex.InnerException != null)
                {
                    _logger.LogError($"内部异常：{ex.InnerException.Message}, StackTrace: {ex.InnerException.StackTrace}");
                }
                return Json(new { code = 1, msg = "获取数据失败：" + ex.Message, count = 0, data = new List<MaintenanceplanDto>() });
            }
        }

        [HttpGet]
        [Route("Get/{id}")]
        public async Task<IActionResult> GetMaintenanceplan(int id)
        {
            try
            {
                _logger.LogInformation($"开始获取点检保养计划，ID：{id}");
                if (id <= 0)
                {
                    _logger.LogWarning($"无效的点检保养计划ID：{id}");
                    return Json(new { success = false, message = "无效的ID" });
                }

                var model = await _maintenanceplanService.GetMaintenanceplan(id);
                if (model == null)
                {
                    _logger.LogWarning($"未找到指定的点检保养计划，ID：{id}");
                    return Json(new { success = false, message = "未找到指定的点检保养计划" });
                }

                _logger.LogInformation($"成功获取点检保养计划，ID：{id}");
                return Json(new { success = true, message = "", data = model });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取点检保养计划失败，ID：{id}");
                return Json(new { success = false, message = "获取数据失败：" + ex.Message });
            }
        }

        [HttpPost]
        [Route("AddMaintenanceplan")]
        public async Task<IActionResult> AddMaintenanceplan(MaintenanceplanDto dto)
        {
            try
            {
                var requestJson = System.Text.Json.JsonSerializer.Serialize(dto);
                _logger.LogInformation($"开始添加点检保养计划，请求数据: {requestJson}");
                
                if (dto == null)
                {
                    _logger.LogWarning("添加点检保养计划时提交的数据为空");
                    return Json(new { success = false, message = "提交的数据不能为空" });
                }

                // 记录详细的请求数据
                _logger.LogInformation($"请求数据详情：Id={dto.Id}, ProjectCode={dto.ProjectCode}, ProjectName={dto.ProjectName}, " +
                    $"ProjectType={dto.ProjectType}, " +
                    $"WhethertoEnable={dto.WhethertoEnable}, ProjectContent={dto.ProjectContent}, Standard={dto.Standard}");

                // 验证字段
                if (string.IsNullOrWhiteSpace(dto.ProjectCode))
                {
                    _logger.LogWarning("添加点检保养计划时项目编码为空");
                    return Json(new { success = false, message = "项目编码不能为空" });
                }

                if (string.IsNullOrWhiteSpace(dto.ProjectName))
                {
                    _logger.LogWarning("添加点检保养计划时项目名称为空");
                    return Json(new { success = false, message = "项目名称不能为空" });
                }

                // 调用服务层方法
                var result = await _maintenanceplanService.AddMaintenanceplan(dto);
                
                _logger.LogInformation($"点检保养计划添加成功，ID：{result}");
                return Json(new { success = true, message = "添加成功", data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加点检保养计划失败");
                return Json(new { success = false, message = "添加失败：" + ex.Message });
            }
        }

        [HttpPost]
        [Route("UpdateMaintenanceplan")]
        public async Task<IActionResult> UpdateMaintenanceplan(MaintenanceplanDto dto)
        {
            try
            {
                var requestJson = System.Text.Json.JsonSerializer.Serialize(dto);
                _logger.LogInformation($"开始更新点检保养计划，请求数据: {requestJson}");
                
                if (dto == null)
                {
                    _logger.LogWarning("更新点检保养计划时提交的数据为空");
                    return Json(new { success = false, message = "提交的数据不能为空" });
                }

                // 验证ID
                if (dto.Id <= 0)
                {
                    _logger.LogWarning($"更新点检保养计划时ID无效：{dto.Id}");
                    return Json(new { success = false, message = "无效的ID" });
                }

                // 记录详细的请求数据
                _logger.LogInformation($"请求数据详情：Id={dto.Id}, ProjectCode={dto.ProjectCode}, ProjectName={dto.ProjectName}, " +
                    $"ProjectType={dto.ProjectType}, " +
                    $"WhethertoEnable={dto.WhethertoEnable}, ProjectContent={dto.ProjectContent}, Standard={dto.Standard}");

                // 验证字段
                if (string.IsNullOrWhiteSpace(dto.ProjectCode))
                {
                    _logger.LogWarning("更新点检保养计划时项目编码为空");
                    return Json(new { success = false, message = "项目编码不能为空" });
                }

                if (string.IsNullOrWhiteSpace(dto.ProjectName))
                {
                    _logger.LogWarning("更新点检保养计划时项目名称为空");
                    return Json(new { success = false, message = "项目名称不能为空" });
                }

                // 调用服务层方法
                var result = await _maintenanceplanService.UpdateMaintenanceplan(dto);
                
                _logger.LogInformation($"点检保养计划更新成功，ID：{result}");
                return Json(new { success = true, message = "更新成功", data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新点检保养计划失败");
                return Json(new { success = false, message = "更新失败：" + ex.Message });
            }
        }

        [HttpPost]
        [Route("Delete/{id}")]
        public async Task<IActionResult> DeleteMaintenanceplan(int id)
        {
            try
            {
                _logger.LogInformation($"开始删除点检保养计划，ID：{id}");
                
                if (id <= 0)
                {
                    _logger.LogWarning($"删除点检保养计划时ID无效：{id}");
                    return Json(new { code = 1, msg = "无效的ID" });
                }

                // 调用服务层方法
                await _maintenanceplanService.DeleteMaintenanceplan(id);
                
                _logger.LogInformation($"点检保养计划删除成功，ID：{id}");
                return Json(new { code = 0, msg = "删除成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"删除点检保养计划失败，ID：{id}");
                return Json(new { code = 1, msg = "删除失败：" + ex.Message });
            }
        }

        // 测试方法：查看数据库中的所有状态值
        [HttpGet]
        public async Task<IActionResult> TestStatus()
        {
            try
            {
                var allData = await _maintenanceplanService.GetMaintenanceplans();
                var statusInfo = allData.Select(x => new {
                    Id = x.Id,
                    ProjectCode = x.ProjectCode,
                    ProjectName = x.ProjectName,
                    Status = x.WhethertoEnable,
                    StatusLength = x.WhethertoEnable?.Length ?? 0,
                    StatusBytes = x.WhethertoEnable != null ? System.Text.Encoding.UTF8.GetBytes(x.WhethertoEnable) : null
                }).ToList();

                return Json(new { 
                    success = true, 
                    data = statusInfo,
                    message = "状态信息获取成功"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取状态信息失败");
                return Json(new { success = false, message = ex.Message });
            }
        }
    }
} 